package com.nyist.diseasepreventionserver.controller;

import com.nyist.diseasepreventionserver.VO.UserHealthVO;
import com.nyist.diseasepreventionserver.VO.UserVO;
import com.nyist.diseasepreventionserver.common.ResponseCode;
import com.nyist.diseasepreventionserver.common.ServerResponse;
import com.nyist.diseasepreventionserver.converter.HealthFormToHealth;
import com.nyist.diseasepreventionserver.converter.UserFormToUser;
import com.nyist.diseasepreventionserver.dto.HealthDTO;
import com.nyist.diseasepreventionserver.dto.UserDTO;
import com.nyist.diseasepreventionserver.entity.HealthDaily;
import com.nyist.diseasepreventionserver.entity.Role;
import com.nyist.diseasepreventionserver.entity.User;
import com.nyist.diseasepreventionserver.form.HealthForm;
import com.nyist.diseasepreventionserver.form.UserForm;
import com.nyist.diseasepreventionserver.service.HealthService;
import com.nyist.diseasepreventionserver.service.UserService;
import com.nyist.diseasepreventionserver.util.MailUtil;
import com.nyist.diseasepreventionserver.util.PropertiesUtil;
import com.nyist.diseasepreventionserver.util.UserHealthUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.security.GeneralSecurityException;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    private static String acceptMail = PropertiesUtil.getProperty("acceptMail");

    @Autowired
    private UserService userService;
    @Autowired
    private HealthService healthService;

    //注册
    @PostMapping("/register")
    public ServerResponse<UserDTO> register(@Valid UserForm userForm,
                                            BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            log.error("【注册失败】参数不正确,userForm={}",userForm);
            return  ServerResponse.createByErrorCodeMessage(ResponseCode.param_error.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        UserDTO userDTO = UserFormToUser.converter(userForm);
        UserDTO one = userService.findOne(userDTO.getUserSid());
        if (one.getUserSid() != null){
            log.error("【注册失败】学号已存在,userSid={}",userForm.getUserSid());
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ID_exists.getCode(),
                    ResponseCode.ID_exists.getDesc());
        }
        userService.register(userDTO);
        return ServerResponse.createBySuccessMessage(ResponseCode.register_success.getDesc());
    }

    //登入
    @PostMapping("/login")
    public ServerResponse userLogin(Integer userSid,String userPassword){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(String.valueOf(userSid), userPassword);

        try {
            subject.login(token);
            //表示登入正常
            UserDTO userDTO = (UserDTO) subject.getPrincipal();
            UserVO userVO = new UserVO();
            userVO.setName(userDTO.getName());
            userVO.setUserSid(userDTO.getUserSid());
            List<Role> roles = userDTO.getRoles();
            //TODO 错误写法 考虑只有单一权限设置 暂时这样写
            List<String> collect = roles.stream().map(Role::getPowerName).collect(Collectors.toList());
            userVO.setRoleName(collect.get(0));

            return ServerResponse.createBySuccess(ResponseCode.success.getDesc(),userVO);
        }catch (UnknownAccountException e){
            //登录失败：学号不存在
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ID_no_exists.getCode(),
                    ResponseCode.ID_no_exists.getDesc());
        }catch (IncorrectCredentialsException e){
            //登入失败：密码不存在
            return ServerResponse.createByErrorCodeMessage(ResponseCode.login_password_error.getCode(),
                    ResponseCode.login_password_error.getDesc());
        }
        //返回前端数据
    }

    //填写健康日报
    @PostMapping("/Whealth")
    public ServerResponse write(@Valid HealthForm healthForm,
                                           BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            log.error("【提交失败】参数不正确,userForm={}",healthForm);
            return  ServerResponse.createByErrorCodeMessage(ResponseCode.param_error.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        HealthDTO healthDTO = HealthFormToHealth.converter(healthForm);
        UserDTO userDTO = healthService.addDaily(healthDTO);
        UserHealthUtil userHealthUtil = new UserHealthUtil();
        UserHealthVO userHealthVO = userHealthUtil.toVO(userDTO);
        if (!userHealthVO.getTemperature().equals("正常(36-37.2)")){
            try {
                MailUtil.send("体温不正常", String.valueOf("学号："+userDTO.getUserSid()+"\n"+
                        "姓名："+userDTO.getUserName()+"\n"+
                        "联系方式："+userDTO.getPhone()),acceptMail);
            } catch (GeneralSecurityException e) {
                e.printStackTrace();
            }
        }else if (!userHealthVO.getHealthStatus().equals("良好")){
            try {
                MailUtil.send("健康状态不正常", String.valueOf("学号："+userDTO.getUserSid()+"\n"+
                        "姓名："+userDTO.getUserName()+"\n"+
                        "联系方式："+userDTO.getPhone()),acceptMail);
            } catch (GeneralSecurityException e) {
                e.printStackTrace();
            }
        }else if (!userHealthVO.getContact().equals("无相关情况")){
            try {
                MailUtil.send("接触相关病人", String.valueOf("学号："+userDTO.getUserSid()+"\n"+
                        "姓名："+userDTO.getUserName()+"\n"+
                        "联系方式："+userDTO.getPhone()),acceptMail);
            } catch (GeneralSecurityException e) {
                e.printStackTrace();
            }
        }
        return ServerResponse.createBySuccess(ResponseCode.success.getDesc(),userHealthVO);
    }
    //查看自己的健康日报
    @GetMapping("/findHealth")
    public ServerResponse findHealth(){
        UserDTO userDTO = (UserDTO) SecurityUtils.getSubject().getPrincipal();
        UserHealthUtil userHealthUtil = new UserHealthUtil();
        UserHealthVO userHealthVO = userHealthUtil.toVO(userDTO);
        return ServerResponse.createBySuccess(userHealthVO);
    }
}
